package com.lyl.mysqlmonitor.driver;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;

import org.slf4j.LoggerFactory;

/**
 * MySQL监控驱动类
 * 实现java.sql.Driver接口，用于拦截JDBC操作
 */
public class MonitorDriver implements Driver {

    private static final String URL_PREFIX = "jdbc:mysql-monitor://";
    private final Driver mysqlDriver;
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(MonitorDriver.class);
    private static volatile boolean isRegistered = false;

    static {
        try {
            // 避免递归创建实例
            if (!isRegistered) {
                isRegistered = true;
                // 注册驱动
                DriverManager.registerDriver(new MonitorDriver());
                LOGGER.info("MySQL索引监控驱动已注册");
            }
        } catch (SQLException e) {
            LOGGER.error("注册MySQL索引监控驱动失败", e);
            throw new RuntimeException("Failed to register MonitorDriver", e);
        }
    }

    public MonitorDriver() throws SQLException {
        // 加载MySQL驱动
        try {
            this.mysqlDriver = new com.mysql.cj.jdbc.Driver();
            LOGGER.debug("MySQL驱动初始化成功");
        } catch (SQLException e) {
            LOGGER.error("MySQL驱动初始化失败", e);
            throw e;
        }
    }

    @Override
    public Connection connect(String url, Properties info) throws SQLException {
        // 检查是否是监控URL
        if (!acceptsURL(url)) {
            return null;
        }

        // 移除监控前缀，获取真实MySQL URL
        String mysqlUrl = "jdbc:mysql://" + url.substring(URL_PREFIX.length());
        LOGGER.debug("转换JDBC URL: {} -> {}", url, mysqlUrl);

        try {
            // 获取真实MySQL连接
            Connection realConnection = mysqlDriver.connect(mysqlUrl, info);

            // 检查连接是否成功
            if (realConnection == null) {
                LOGGER.error("无法获取数据库连接，URL: {}", mysqlUrl);
                throw new SQLException("无法获取数据库连接，请检查URL、用户名和密码");
            }

            LOGGER.debug("创建数据库监控连接");
            // 返回代理连接
            return new MonitorConnection(realConnection);
        } catch (SQLException e) {
            LOGGER.error("连接数据库失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public boolean acceptsURL(String url) throws SQLException {
        return url != null && url.startsWith(URL_PREFIX);
    }

    @Override
    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
        return mysqlDriver.getPropertyInfo(url, info);
    }

    @Override
    public int getMajorVersion() {
        return mysqlDriver.getMajorVersion();
    }

    @Override
    public int getMinorVersion() {
        return mysqlDriver.getMinorVersion();
    }

    @Override
    public boolean jdbcCompliant() {
        return true;
    }

    /**
     * 检查驱动是否已注册
     * @return 如果驱动已注册返回true，否则返回false
     */
    public static boolean isRegistered() {
        return isRegistered;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return mysqlDriver.getParentLogger();
    }
}
